<link rel="stylesheet" href="module/dtree/dtree.css"/>
<link rel="stylesheet" href="module/dtree/font/dtreefont.css"/>
<link rel="stylesheet" href="assets/css/userInfo.css">

<div class="layui-row layui-col-space15" style="height: 100%;margin: 0" id="userInfoForm">
    <div class="layui-col-sm12 layui-col-md4 layui-col-lg2" style="height: 100%">
        <div class="layui-card" style="height: 100%;">
            <!--            <div class="layui-card-header">-->
            <!--                <h2 class="header-title">部门管理</h2>-->
            <!--                <button type="button" class="layui-btn layui-btn-sm">-->
            <!--                    <i class="layui-icon">&#xe654;</i>-->
            <!--                </button>-->
            <!--            </div>-->
            <div class="layui-card-body mini-bar" id="ltTree">

            </div>
        </div>
    </div>
    <div class="layui-col-sm12 layui-col-md8 layui-col-lg10" style="height: 100%; background: #fff">
        <div class="layui-card-body" style="background: #F5F6F7;">
            <div class="layui-form toolbar">
                <div class="search">
                    <input id="businessUser-search-value" class="layui-input search-input" type="text"
                           placeholder="输入姓名关键字"/>
                    <button class="layui-btn icon-btn" id="businessUser-search-btn"><img src="assets/images/search.png" alt=""></button>
                </div>
                <button id="businessUser-btn-add" class="layui-btn icon-btn" style="background: #38B7CB;"><i class="layui-icon">&#xe654;</i>添加用户
                </button>
            </div>
            <table class="layui-table" id="businessUser-table" lay-filter="businessUser-table"></table>
        </div>
    </div>
</div>

<!-- 表格头像 -->
<script type="text/html" id="businessUser-table-avatar">
    <img src="{{d.photo}}" alt="" style="width: 24px;height: 24px">
</script>

<!-- 表格操作列 -->
<script type="text/html" id="businessUser-table-bar">
    <a class="" lay-event="edit" title="编辑" style="margin-right: 10px"><img src="assets/images/edit.png" alt=""
                                                                            style="width: 16px"></a>
    <a class="" lay-event="reset" title="重置密码" style="margin-right: 10px"><img src="assets/images/reset.png" alt=""
                                                                               style="width: 16px"></a>
    <a class="" lay-event="del" title="删除"><img src="assets/images/del.png" alt="" style="width: 16px"></a>
</script>

<!-- 表格状态列 -->
<script type="text/html" id="businessUser-tpl-state">
    <input type="checkbox" lay-filter="businessUser-tpl-state" value="{{d.user_id}}" lay-skin="switch"
           {{d.status==0?'checked':''}}/>
</script>

<script type="text/html" id="add-department-model">
    <form id="add-department-form" lay-filter="add-department-form" class="layui-form model-form">
        <div class="layui-form-item">
            <label class="layui-form-label">部门名称</label>
            <div class="layui-input-block">
                <input type="text" name="name" required lay-verify="required" class="layui-input"
                       placeholder="">
            </div>
        </div>
        <div class="layui-form-item model-form-footer">
            <button class="layui-btn" lay-filter="department-form-submit" lay-submit style="background: #38B7CB;">确定</button>
            <button class="layui-btn layui-btn-primary" ew-event="closeDialog" type="button">取消</button>
        </div>
    </form>
</script>

<script>
    layui.use(['layer', 'dtree', 'config', 'table', 'admin', 'form'], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            config = layui.config,
            table = layui.table,
            admin = layui.admin,
            dtree = layui.dtree,
            entCode = '',
            form = layui.form,
            tableObj = [];

        var getEntChildren = function (arr, parent) {
            let children = [];
            arr.forEach(d => {
                if (d.pid === parent.ent_id) {
                    d.id = d.ent_id;
                    d.title = d.name;
                    d.basicData = {'entCode': d.entCode, 'entId': d.ent_id}
                    children.push(getEntChildren(arr, d))
                }
            })
            parent.children = children;
            return parent;
        }

        admin.req('api-sys/api/enterprise/list', {}, function (res) {
            var data = res.data;
            if (data) {
                data.forEach(d => {
                    if (d.top_pid === 0) {
                        d.id = d.ent_id;
                        d.title = d.name;
                        d.basicData = {entCode: d.entCode, 'entId': d.ent_id};
                        tableObj.push(getEntChildren(data, d));
                    }
                })
                return tableObj;
            }

        })

        setTimeout(function () {
            $('#ltTree').html('');
            var LtTerr = dtree.render({
                elem: '#ltTree',
                data: tableObj,
                skin: 'layui',
                icon: -1,
                iconfont: ["layui-icon"],
                iconfontStyle: [
                    {
                        toolbarExt: "layui-icon-addition"
                    }
                ],
                toolbar: true,
                toolbarShow: [], // 默认按钮制空
                toolbarExt: [
                    {
                        toolbarId: "add",
                        title: "添加",
                        handler: function (node, $div) {
                            admin.putTempData('department_data', node);
                            layer.msg(JSON.stringify(node));
                            layer.open({
                                type: 1,
                                title: '添加部门',
                                area: '590px',
                                content: $('#add-department-model').html(),
                                success: function (layero, index) {

                                }
                            })
                        }
                    },
                    {
                        toolbarId: "del",
                        // icon: "dtree-icon-roundclose",
                        title: "删除",
                        handler: function (node, $div) {
                            console.log($div)
                            // dTree.partialRefreshDel($div); // 这样即可删除节点
                            layer.confirm('确定要删除吗？', function (i) {
                                layer.close(i);
                                layer.load(2);
                                admin.req('api-sys/api/enterprise/del/' + node.nodeId, {}, function (data) {
                                    layer.closeAll('loading');
                                    if (data.code == 0) {
                                        layer.msg(data.msg, {icon: 1, time: 500});
                                        // dtree.partialRefreshDel($div)
                                    } else {
                                        layer.msg(data.msg, {icon: 2, time: 500});
                                    }
                                }, 'DELETE');
                            });
                            return false;
                        }
                    }
                ]
            })
        }, 300)

        form.on('submit(department-form-submit)', function (data) {
            var department_data = admin.getTempData('department_data');
            var param = {
                name: data.field.name,
                pid: department_data.nodeId,
            }
            layer.load(2);
            admin.req('api-sys/api/enterprise/addEntUser?access_token=' + config.getToken().access_token, JSON.stringify(param), function (data) {
                layer.closeAll('loading');
                if (data.code == 0) {
                    layer.msg(data.msg, {icon: 1, time: 500});
                    admin.finishPopupCenter();
                } else {
                    layer.msg(data.msg, {icon: 2, time: 500});
                }
            }, 'POST');
            // return false;
        })

        dtree.on('node(ltTree)', function (obj) {
            var basicData = JSON.parse(obj.param.basicData);
            entCode = basicData.entCode;
            var myTable = table.render({
                elem: '#businessUser-table',
                where: {
                    access_token: config.getToken().access_token,
                    entCode
                },
                url: config.base_server + 'api-sys/api/sysUser/list',
                method: 'GET',
                page: {
                    layout: ['prev', 'page', 'next'],
                    theme: '#38B7CB'
                },
                height: 'full',
                skin: 'nob',
                even: true,
                cols: [[
                    {type: 'checkbox'},
                    {
                        field: 'photo',
                        title: '头像',
                        templet: "#businessUser-table-avatar",
                        width: 150,
                        style: 'color: #778192'
                    },
                    {field: 'username', title: '账号', width: 250, style: 'color: #778192'},
                    {field: 'nickname', title: '姓名', style: 'color: #778192'},
                    {field: 'phone', title: '手机号', style: 'color: #778192'},
                    {
                        title: '性别', templet: function (d) {
                            return d.sex == 0 ? "男" : "女"
                        }
                    },
                    {field: 'status', title: '状态', templet: '#businessUser-tpl-state'},
                    {toolbar: '#businessUser-table-bar', title: '操作', align: 'center'}
                ]]
            })

            $('#businessUser-search-btn').click(function () {
                var value = $('#businessUser-search-value').val();
                var data = {};
                if(value)
                    data.nickname = value;
                data["access_token"] = config.getToken().access_token;
                data.entCode = entCode;
                myTable.reload({where: data});
            })

            $('#businessUser-btn-add').click(function () {
                showAddAndEditModel({entCode});
            })

            var showAddAndEditModel = function (data) {
                var title = data.user_id ? '修改用户' : '添加用户';
                admin.putTempData('t_user', data);
                admin.popupCenter({
                    title: title,
                    path: 'pages/business/userForm.html',
                    area: '590px',
                    finish: function () {
                        table.reload('businessUser-table', {});
                    }
                });
            }

            // 表格操作栏点击事件
            table.on('tool(businessUser-table)', function (obj) {
                var data = obj.data;
                var layEvent = obj.event;

                if(layEvent === 'edit') {
                    showAddAndEditModel(data);
                }else if(layEvent === 'del') {
                    doDelete(obj);
                } else if(layEvent === 'reset') {
                    layer.confirm('确定重置此用户的密码吗？', function (i) {
                        layer.close(i);
                        layer.load(2);
                        admin.req('api-sys/api/sysUser/resetMima?access_token='+config.getToken().access_token+'&username='+obj.data.username, {}, function (data) {
                        // admin.req('api-sys/api/sysUser/resetMima?access_token=?access_token=429d363e-0637-4c97-bd9f-d349f5d4b159&username='+obj.data.username, {}, function (data) {
                            layer.closeAll('loading');
                            if (data.code == 0) {
                                layer.msg(data.msg, {icon: 1, time: 500});
                            } else {
                                layer.msg(data.msg, {icon: 2, time: 500});
                            }
                        }, 'PATCH');
                    });
                }
            })

            var doDelete = function (obj) {
                console.log(obj)
                layer.confirm('确定要删除吗？', function (i) {
                    layer.close(i);
                    layer.load(2);
                    admin.req('api-sys/api/sysUser/del/' + obj.data.user_id, {}, function (data) {
                        layer.closeAll('loading');
                        if (data.code == 0) {
                            layer.msg(data.msg, {icon: 1, time: 500});
                            obj.del();
                        } else {
                            layer.msg(data.msg, {icon: 2, time: 500});
                        }
                    }, 'DELETE');
                });
            }
        })

    })
</script>